package com.fw.application.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.UserController;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.UserAnswerForm;
import com.fw.system.web.model.vo.AnswerDetailVo;
import com.fw.system.web.model.vo.InterAnswerVO;
import com.fw.system.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 题库表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/web/answer")
@CrossOrigin
@Api(tags = "答题相关")
public class TbAnswerController implements UserController {


    @Autowired
    private IdXD idXD;
    @Autowired
    private ITbAnswerService answerService;
    @Autowired
    private ITbUserResultService resultService;
    @Autowired
    private ITbSysRuleService ruleService;
    @Autowired
    private ITbIntegralLogService integralLogService;
    @Autowired
    private ITbAnswerDetailService detailService;

    @GetMapping("/getAnswer")
    @ApiOperation("抽取题目")
    public Result<List<AnswerDetailVo>> getAnswer() {

        List<String> answerIds = answerService.list(Wrappers.<TbAnswer>lambdaQuery().last("ORDER BY RAND() limit  5")).parallelStream()
                .map(map -> map.getId()).collect(Collectors.toList());
        List<AnswerDetailVo> collect = answerIds.stream().map(map -> {
            List<TbAnswerDetail> details = detailService.list(Wrappers.<TbAnswerDetail>lambdaQuery().eq(TbAnswerDetail::getAnswerId, map));
            AnswerDetailVo build = Builder.of(AnswerDetailVo::new)
                    .build();
            BeanUtil.copyProperties(answerService.getById(map), build);
            build.setDetail(details);
            return build;
        }).collect(Collectors.toList());
        return success(collect);
    }


    @PostMapping("/userAnswer")
    @ApiOperation("用户答题 ） ")
    @Transactional(rollbackFor = Exception.class)
    public Result userAnswer(@RequestBody List<UserAnswerForm> userAnswerForm) {

        TbUser user = this.getUser();
        TbUserResult result = new TbUserResult();
        ArrayList<AnswerDetailVo> answerDetailVos = new ArrayList<>();
        InterAnswerVO interAnswerVO = new InterAnswerVO();
        userAnswerForm.stream().forEach(item -> {
            TbAnswer answer = answerService.getById(item.getId());
            //添加答题情况记录
            result.setCreateTime(LocalDateTime.now());
            result.setUserId(user.getId());
            result.setAnswerId(item.getId());
            result.setId(idXD.nextId());
            //用户选项逗号隔开字符串
            String collect = item.getIds().stream().collect(Collectors.joining(","));
            result.setUserResult(collect).insert();
            //比对答案
            List<TbAnswerDetail> detailList = detailService.list(Wrappers.<TbAnswerDetail>lambdaQuery()
                    .eq(TbAnswerDetail::getAnswerId, item.getId())
                    .eq(TbAnswerDetail::getIsExactness, 1));
            List<TbAnswerDetail> list = detailService.list(Wrappers.<TbAnswerDetail>lambdaQuery()
                    .in(TbAnswerDetail::getId, item.getIds())
                    .eq(TbAnswerDetail::getAnswerId, item.getId())
                    .eq(TbAnswerDetail::getIsExactness, 1));
            if (list.size() != detailList.size()) {
                //记录错题
                List<TbAnswerDetail> notAnswer = detailService.list(Wrappers.<TbAnswerDetail>lambdaQuery()
                        .in(TbAnswerDetail::getId, item.getIds()));
                AnswerDetailVo vo = new AnswerDetailVo();
                vo.setDetail(detailList);
                vo.setAnswerTitle(answer.getAnswerTitle());
                vo.setAnswerType(answer.getAnswerType());
                vo.setYouAnswer(notAnswer);
                vo.setAnswerNumber(item.getAnswerNumber());
                vo.setAnswerResult(answer.getAnswerResult());
                answerDetailVos.add(vo);
            }

        });
        interAnswerVO.setAnswerDetailVos(answerDetailVos);
        Integer integral = Integer.parseInt(ruleService.getById(1).getRuleValue()) * (userAnswerForm.size() - answerDetailVos.size());
        if (integral > 0) {
            //验证今日获取积分
            TbIntegralLog log = integralLogService.getOne(Wrappers.<TbIntegralLog>lambdaQuery().eq(TbIntegralLog::getIntegralName, "答题获得积分").eq(TbIntegralLog::getUserId, user.getId())
                    .last("and to_days(create_time) = to_days(now())"));
            TbSysRule startAndEndTime = ruleService.getById(8);
            if (log == null && LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) <= 0) {
                user.setIntegral(user.getIntegral() + integral).updateById();
                integralLogService.addIntegral(Builder
                        .of(TbIntegralLog::new).with(TbIntegralLog::setIntegralName, "答题获得积分")
                        .with(TbIntegralLog::setUserId, user.getId())
                        .with(TbIntegralLog::setIntegralNum, integral)
                        .with(TbIntegralLog::setIsType, 1).build());
                interAnswerVO.setInterNum(integral);
            }
        }

        return success(interAnswerVO);
    }


}

